package nnweboa;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.jsp.JspWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class URlManager {
	private ArrayList<UrlContent> ulist = new ArrayList<UrlContent>();
	private Iterator<UrlContent> iter;

	public URlManager(int right, String path) throws DocumentException,
			IOException {

		SAXReader xreader = new SAXReader();

		Document xmldocment = xreader.read(path + File.separator
				+ "functionwork.xml");
		Element root = xmldocment.getRootElement();
		@SuppressWarnings("unchecked")
		Iterator<Element> itern = root.elementIterator();
		while (itern.hasNext()) {
			Element item = itern.next();

			if (Integer.parseInt(item.attributeValue("right")) == right) {
				@SuppressWarnings("unchecked")
				Iterator<Element> iterelement = item.elementIterator();
				while (iterelement.hasNext()) {
					Element iitem = iterelement.next();
					UrlContent ucontent = new UrlContent(
							iitem.attributeValue("type"),
							iitem.attributeValue("text"));
					ulist.add(ucontent);
				}
				break;
			}
		}
		iter = ulist.iterator();

	}

	public int getCount() {
		return ulist.size();
	}

	public ArrayList<UrlContent> getlist() {
		ArrayList<UrlContent> list = new ArrayList<UrlContent>();

		while (iter.hasNext()) {
			list.add(iter.next());
			if (list.size() > 18) {
				break;
			}
		}
		if (list.size() != 0) {
			return list;
		} else {
			return null;
		}
	}

	public static String geturl(String dir, String type, String cookiename,
			JspWriter out) throws DocumentException, IOException {
		String page = "error.jsp";

		SAXReader xreader = new SAXReader();
		Document xmldocment = xreader.read(dir + File.separator
				+ "functionwork.xml");
		Element root = xmldocment.getRootElement();
		@SuppressWarnings("unchecked")
		Iterator<Element> itern = root.elementIterator();
		ArrayList<Element> e = new ArrayList<Element>();
		while (itern.hasNext()) {
			Element item = itern.next();
			@SuppressWarnings("unchecked")
			Iterator<Element> subiter = item.elementIterator();
			while (subiter.hasNext()) {
				e.add(subiter.next());
			}
		}
		for (Element item : e) {
			
			if (item.attributeValue("type").trim()
					.compareToIgnoreCase(type.trim()) == 0) {
				if (item.attributeValue("url").compareToIgnoreCase(
						"editpssword.jsp") == 0) {
					page = item.attributeValue("url") + "?user=" + cookiename;
				} else {
					page = item.attributeValue("url");
				}
				break;
			}
		}

		return page;
	}
}
